//
//  ZPickerCollection.swift
//  swift-weibo
//
//  Created by zero on 17/3/29.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

//  重用标识符
private let pickerID = "pickerID"
// 计算cell的间距
private let itemMargin: CGFloat = 5
// 计算cell的宽高
private let cellWH = (ScreenWidth - 2 * 10 - 2 * itemMargin) / 3 

class ZPickerCollection: UICollectionView {

  
    //  图片数组
    var imgList:[UIImage] = [UIImage]()
    
    //  点击加号添加图片的闭包
    var addPicture:(()->())?
    

    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: layout)
        
        //  设置layout的属性
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
        //  布局
        setupUI()
    }
    
    //  添加图片
    func addImage(image:UIImage){
        
        if imgList.count < 9 {
            //  添加到数组中
            isHidden = false
            
            imgList.append(image)
            
            //  修改大小
            updateSize(count: imgList.count)
            
            //  刷新数据
            reloadData()
        }
    }
    
    //  修改发小
    fileprivate func updateSize(count:Int){
        
        let row = count / 3 != 3 ? CGFloat(count / 3 + 1) : 3
        
        //  更新约束
        self.snp.updateConstraints { (make) in
            
            make.size.equalTo(CGSize(width: ScreenWidth - 20, height: row * (cellWH + itemMargin)))
        }
        
        //  刷新
        layoutIfNeeded()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //  布局
    fileprivate func setupUI(){
        
        backgroundColor = UIColor.clear
        //  注册
        register(ZPickerCollectionCell.self, forCellWithReuseIdentifier: pickerID)
        dataSource = self
        delegate = self
        
        self.snp.makeConstraints { (make) in
            
            make.size.equalTo(CGSize(width: 0, height: 0))
        }
    }
    
    
}
//MARK: 数据源代理
extension ZPickerCollection:UICollectionViewDataSource,UICollectionViewDelegate{

    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if imgList.count > 0 && imgList.count < 9{
            
            return imgList.count + 1
        }
        
        return imgList.count
    }


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pickerID, for: indexPath) as! ZPickerCollectionCell
    
        if indexPath.item == imgList.count {
            
            cell.img = nil
            
        }else{
            cell.img = imgList[indexPath.item]
        }
        
        cell.deletePictureBtn = {[weak self] () -> () in
            
            self?.imgList.remove(at: indexPath.item)
            //  修改大小
            if self?.imgList.count == 0 {
                
                self?.isHidden = true
            }
            self?.reloadData()
            
        }
        
        return cell
    }
    
    //  取消选中
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        deselectItem(at: indexPath, animated: true)
        
        //  加号的点击事件
        if indexPath.item == imgList.count{
            
            addPicture?()
        }
    }
}

//MARK: 自定义cell
class ZPickerCollectionCell: UICollectionViewCell {
    
    //  点击删除的闭包
    var deletePictureBtn:(()->())?
    
    //  接收图片
    var img:UIImage?{
        
        didSet{
            
            if img == nil {
                
                imgCell.image = UIImage(named: "compose_pic_add")
                imgCell.highlightedImage = UIImage(named:"compose_pic_add_highlighted")
                
                btnColose.isHidden = true
                
            }else{
                
                imgCell.image = img
                imgCell.highlightedImage = nil
                
                btnColose.isHidden = false
            }
            
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //  布局
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI(){
        
        //  添加
        contentView.addSubview(imgCell)
        
        //  约束
        imgCell.snp.makeConstraints { (make) in
            
            make.edges.equalTo(contentView)
        }
        
        //  添加删除按钮
        contentView.addSubview(btnColose)
        
        //  约束
        btnColose.snp.makeConstraints { (make) in
            
            make.top.equalTo(imgCell)
            make.trailing.equalTo(imgCell)
        }
    }
    
    //  懒加载
    private lazy var imgCell = UIImageView()
    
    // compose_photo_close
    private lazy var btnColose:UIButton = {
        
       let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), for: .normal)
        
        btn.addTarget(self, action: #selector(delatePicture), for: .touchUpInside)
        
        return btn
    }()
    
    @objc fileprivate func delatePicture(){
        
        //  调用闭包
        deletePictureBtn?()
        
    }
    
}
